<template>
  <div id="goTop">
    <div class="icons" v-show="visiable" @click="handleScrollTop">
      <i class="icons-top">
        <span class="text">返回顶部</span>
      </i>
    </div>
  </div>
</template>
 
<script>
export default {
  name: 'XtxBacktop',
  data() {
    return {
      scrollTop: null, //初始化scrollTop
      visiable: false //默认不显示
    }
  },
  methods: {
    handleScroll() {
      this.scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      if (this.scrollTop > 500) {
        this.visiable = true
      } else {
        this.visiable = false
      }
    },

    handleScrollTop() {
      let timer = null,
        that = this
      cancelAnimationFrame(timer)
      timer = requestAnimationFrame(function fn() {
        if (that.scrollTop > 0) {
          that.scrollTop -= 50
          document.body.scrollTop = document.documentElement.scrollTop =
            that.scrollTop
          timer = requestAnimationFrame(fn)
        } else {
          cancelAnimationFrame(timer)
          that.visiable = false
        }
      })
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll)
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>
 
<style lang='less' scoped>
.icons {
  position: fixed;
  right: 5rem;
  bottom: 8rem;
  width: 4rem;
  height: 4rem;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.65);
}

.icons:hover {
  background-color: rgba(128, 128, 128, 0.8);
  .text {
    color: rgba(128, 128, 128, 0.8);
  }
}

.icons-top {
  position: relative;
  display: block;
  width: 4rem;
  height: 4rem;
  background-size: 2rem;
  background-repeat: no-repeat;
  background-position: center center;
  background-image: url('');
}
.text {
  color: rgba(0, 0, 0, 0.65);
  position: absolute;
  bottom: 60px;
  font-size: 14px;
}
</style>
